"use strict"

var express = require('express');
var _ = require('underscore')
var app = express();

app.use(express.static(__dirname + '/app'));
app.use(express.static(__dirname + '/compass'));
app.use('/js/libs/', express.static(__dirname + '/components/'));
app.use('/js/libs/', express.static(__dirname + '/node_modules/requirejs/'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use(express.bodyParser());

app.get   ('/messages',     index);
app.get   ('/messages/:id', show);
app.post  ('/messages',     create);
app.put   ('/messages/:id', update);
app.delete('/messages/:id', destroy);

app.listen(8081, function() {
  console.log('Running on http://localhost:8081');
});

// var messages = [
//   { id: 1, name: 'n01', text: 'tt01', title: '001', order: 10, completed: false },
//   { id: 2, name: 'n02', text: 'tt02', title: '002', order: 20, completed: false }
// ];

// function getMessages(req, res, next) {
//   res.send(messages);
// };

// function postMessage(req, res, next) {
//   res.send(messages[0]);
// }

var mongoose = require('mongoose/');
var config = require('./config'); // Local congig file to hide creds
var db = mongoose.connect(config.creds.mongoose_auth),
Schema = mongoose.Schema;

var MessageSchema = new Schema({
  name: String,
  text: String,
  title: String,
  image: String,
  order: Number,
  completed: Boolean,
  date: Date
});

mongoose.model('Message', MessageSchema);
var Message = mongoose.model('Message');

function index(req, res, next) {
  Message.find().limit(100).execFind(function(err, data) {
    if (!err) {
      res.send(data);
    }
  });
}

function show(req, res, next) {
  Message.findById(req.params.id, function(err, data) {
    if (!err) {
      res.send(data);
    }
  });
}

function create(req, res, next) {
  var message = new Message();
  message.name = req.body.name;
  message.text = req.body.text;
  message.title = req.body.title;
  message.image = req.body.image;
  message.order = req.body.order;
  message.completed = req.body.completed;
  message.date = new Date()
  message.save(function(err) {
    res.send(message);
  });
}

function update(req, res, next) {
  var message = new Message();
  Message.findById(req.params.id, function(err, message) {
    message.name = req.body.name;
    message.text = req.body.text;
    message.title = req.body.title;
    message.image = req.body.image;
    message.order = req.body.order;
    message.completed = req.body.completed;
    message.date = new Date()
    message.save(function(err) {
      res.send(message);
    });
  })
}

function destroy(req, res, next) {
  Message.findById(req.params.id, function (err, message) {
    return message.remove(function (err) {
      if (!err) {
        return res.send('');
      }
    });
  })
}
